package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "MQSectkillOrderListener",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
@Slf4j
public class MQSectkillOrderListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage message) {
         log.info("已经进入到下单的队列中......");
        Long seckillId = message.getSeckillId();
        Integer time = message.getTime();
        String token = message.getToken();
        Long phone = message.getUserPhone();
        String tag = "";

        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setTime(time);
        orderMQResult.setToken(token);

        try {
            //int i= 1/0;
             //执行秒杀业务逻辑
            String orderNo = orderInfoService.doSeckill(seckillId, time, phone);
            tag =  MQConstant.ORDER_RESULT_SUCCESS_TAG;
            //发送延迟消息
            orderMQResult.setOrderNo(orderNo);
            MessageBuilder<OrderMQResult> messageBuilder = MessageBuilder.withPayload(orderMQResult);
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,messageBuilder.build(),5000,5);
        }catch (Exception e){
             tag = MQConstant.ORDER_RESULT_FAIL_TAG;
             orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
             orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
        }
        //往通知队列中发送消息
      rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC + ":" + tag,orderMQResult);

    }
}
